//
//  GiveSearchVC.swift
//  zhonglb_iOS
//
//  Created by lxm on 2021/12/2.
//

import UIKit

class TransFerSearch: ZMViewController, UITableViewDelegate, UITableViewDataSource, ListRequestObjct {
    
    //MARK:--------------------属性--------------------
    var listData = [TransferInput.UserModel]()
    var page = 1
    var pageSize = 10
    var refreshScrollView : UIScrollView {
        tableView
    }
    var lastWord = ""
    var onSelect : ((_ user : TransferInput.UserModel)->())?
    var curretUser = ZMUtil.fastNilBehavior(type: TransferInput.UserModel.self)
    //MARK:--------------------UI控件--------------------
    @IBOutlet weak var searchText: UITextField!
            
    @IBOutlet weak var tableView: UITableView!
    
    var footerView = UIView()
    var sureButton = ZMUtil.button(title: "确认", font: UIFont.systemFont(ofSize: 16, weight: .medium), color: .white).then({$0.backgroundColor = Style.mainColor})
    
    var headerView = UIView().then { v in
        let line = UIView()
        v.addSubview(line)
        line.snp.makeConstraints { make in
            make.left.equalToSuperview().offset(16)
            make.right.equalToSuperview().offset(-16)
            make.bottom.equalToSuperview()
            make.height.equalTo(0.5)
        }
        line.backgroundColor = Style.lineColor
        let label = ZMUtil.label(title: "请选择转账对象", color : UIColor.zm.color666666(), font: UIFont.systemFont(ofSize: 14))
        v.addSubview(label)
        
        label.snp.makeConstraints { make in
            make.left.equalToSuperview().offset(16)
            make.top.equalToSuperview().offset(24)
        }
    }
    
    //MARK:--------------------生命周期--------------------
    override func viewDidLoad() {
        super.viewDidLoad()
        setUI()
        addConstraints()
        bindAction()
    }
    //MARK:--------------------UI--------------------
    func setUI() {
        title = "转账"
        searchText.MaxCharcterCount = 11
        searchText.delegate = self
        if let btn = searchText.value(forKey: "_clearButton") as? UIButton {
            btn.setImage(UIImage.init(named: "clear_btn"), for: .normal)
            btn.setImage(UIImage.init(named: "clear_btn"), for: .selected)
        }
        
        tableView.delegate = self
        tableView.dataSource = self
        tableView.zm.register(nibName: "GiveSearchUserCell", reuserId: "GiveSearchUserCell")
        tableView.contentInset = UIEdgeInsets(top: 8, left: 0, bottom: 0, right: 0)
    
        tableView.tableHeaderView = headerView
//        tableView.tableFooterView = footerView
        footerView.addSubview(sureButton)
        footerView.frame = CGRect(x: 0, y: 0, width: SCREEN_W, height: 100)
        headerView.frame = CGRect(x: 0, y: 0, width: SCREEN_W, height: 56)
        
        sureButton.layer.cornerRadius = 23
        
        addNodataScrollView(scrollView: tableView)
        emptyImg = "kong_sc"
        tableView.mj_header?.beginRefreshing()
        
    }
    
    func addConstraints() {
        sureButton.snp.makeConstraints { make in
            make.centerX.equalToSuperview()
            make.top.equalToSuperview().offset(46)
            make.left.equalToSuperview().offset(16)
            make.height.equalTo(46)
        }
    }
    
    //MARK:--------------------methods--------------------
    func bindAction() {
        searchText.rx.text.orEmpty.subscribe(onNext:{ [unowned self] resp in
            if resp.count == 0, lastWord.count > 0 {
                self.tableView.mj_header?.beginRefreshing()
            }
            self.lastWord = resp
        }).disposed(by: disposeBag)
        
        curretUser.subscribe(onNext:{ [unowned self] resp in
            guard let resp = resp else {
                self.headerView.isHidden = true
                self.tableView.reloadData()
                return
            }
            self.headerView.isHidden = false
            self.tableView.reloadData()
        }).disposed(by: disposeBag)
    }
    
    @IBAction func searchClick(_ sender: Any) {
        _ = onSearch()
    }
    
    func onSearch() -> Bool {
        if searchText.text!.isEmpty {
            ZMToast.showToast(title: "请输入搜索内容")
            return false
        }
        view.endEditing(true)
        page = 1
        loadList(searchText.text!)
        return true
    }
    
    func loadList(_ keyword : String) {
        let pa = ["phone" : keyword]
        ZMToast.showActivity()
        MineAPI.searchUser(pa).rxRequest(type: TransferInput.UserModel.self).subscribe(onNext:{ [unowned self] resp in
            self.curretUser.accept(resp)
            ZMToast.hiddenActivity()
        }, onError: { _ in
            self.curretUser.accept(nil)
        }).disposed(by: disposeBag)
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        tableView.mj_footer?.isHidden = listData.count == 0
        return curretUser.value == nil ? 0 : 1
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "GiveSearchUserCell") as! GiveSearchUserCell
        let data = curretUser.value!
        cell.rightIcon.isHidden = true
        cell.avatar.zm.setImage(urlStr: data.avatar)
        cell.nickname.text = data.nickname
        cell.histroy.text = "手机号：" + data.phone.zm.hidPhone()
        cell.lineView.isHidden = true
        cell.backgroundColor = .clear
        return cell
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        guard let onSelect = onSelect else {return}
        let data = curretUser.value!
        onSelect(data)
        self.navigationController?.popViewController(animated: true)
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        GiveSearchUserCell.cellHieght
    }
}


extension TransFerSearch : UITextFieldDelegate {
    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        return onSearch()
    }
    
    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        let regex = "^[0-9]*$"
        let ok = NSPredicate(format: "SELF MATCHES %@",regex).evaluate(with: string)
        return ok
    }
}
